package com.cqeec.waimaidemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqeec.waimaidemo.dto.DishDto;
import com.cqeec.waimaidemo.entity.Dish;
import com.cqeec.waimaidemo.entity.DishFlavor;
import com.cqeec.waimaidemo.mapper.DishMapper;
import com.cqeec.waimaidemo.service.DishFlavorService;
import com.cqeec.waimaidemo.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    DishFlavorService dishFlavorService;
    @Override
// 需要同时插入两张表数据，要么都成功，要么都失败
    @Transactional
    public void saveWithFlavors(DishDto dishDto) {
// 先保存dish
        this.save(dishDto);
        List<DishFlavor> dishFlavors=dishDto.getFlavors();
        for (int i =0;i<dishFlavors.size();i++){
            dishFlavors.get(i).setDishId(dishDto.getId());
        }

//        List<DishFlavor> dishFlavors = DishDto.getFlavors().stream().map(item->{
//            item.setDishId(dishDto.getId());
//            return item;
//        }).collect(Collectors.toList());
//        dishFlavorService.saveBatch(dishFlavors);
    }

    /**
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdFlavors(Long id) {
        Dish dish = this.getById(id);
        DishDto dishDto=new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        LambdaQueryWrapper<DishFlavor> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorService.list(wrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    /**
     * @param dishDto
     */
    @Override
    @Transactional
    public void updateWithFlavors(DishDto dishDto) {
        this.updateById(dishDto);
//        删除之前dish_flavors 这张表的相关数据
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(wrapper);
        //        插入现在用户提供的数据
        List<DishFlavor> dishFlavors=dishDto.getFlavors();
        dishFlavors.forEach(x->x.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(dishFlavors);
    }
}
